package com.gsy.controller.student;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gsy.aop.annotation.TokenValid;
import com.gsy.entity.ReadEntity;
import com.gsy.entity.UserEntity;
import com.gsy.request.AddNoticeRequest;
import com.gsy.service.ReadService;
import com.gsy.service.UserService;
import com.gsy.vo.GetNoticeVO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import com.gsy.aop.annotation.ParameterValid;
import com.gsy.enumerate.SystemStatusEnum;
import com.gsy.response.BaseResponse;

import com.gsy.service.NoticeService;
import com.gsy.entity.NoticeEntity;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gsy
 * @since 2022-03-03
 */
@RestController
@RequestMapping(consumes = "application/json", produces = "application/json")
@Api(value = "controller", tags = {"tb_notice 操作接口"})
public class NoticeController {

    private final static Logger LOGGER = LoggerFactory.getLogger(NoticeController.class);

    @Resource
    private NoticeService noticeService;

    @Resource
    private UserService userService;

    @Resource
    private ReadService readService;

    /**
     * 删除tb_notice信息
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除tb_notice信息", notes = "根据请求参数信息删除tb_notice信息")
    @DeleteMapping("admin/delNotice/{id}")
    @TokenValid
    public BaseResponse deleteNotice(@PathVariable Integer id) {
        NoticeEntity entity = noticeService.getById(id);

        if (entity == null) {
            return new BaseResponse(SystemStatusEnum.FAIL.getCode(), "不存在该条信息！");
        }

        noticeService.removeById(id);
        return new BaseResponse(SystemStatusEnum.SUCCESS);

    }


    /**
     * 发布通知
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "发布通知", notes = "发布通知")
    @PostMapping("admin/announce")
    @ParameterValid(apiName = "发布通知", formatObj = AddNoticeRequest.class)
    @TokenValid
    public BaseResponse addNotice(@RequestBody AddNoticeRequest request) {

        NoticeEntity entity = new NoticeEntity();
        BeanUtils.copyProperties(request, entity);

        Boolean flag = noticeService.save(entity);
        if (flag) {
            return new BaseResponse(SystemStatusEnum.SUCCESS);
        } else {
            return new BaseResponse(SystemStatusEnum.FAIL.getCode(), "新增失败！");
        }
    }


    /**
     * 获取所有通知与数量(分页获取)
     *
     * @return
     */
    @ApiOperation(value = "获取所有通知与数量(分页获取)", notes = "获取所有通知与数量(分页获取)")
    @GetMapping("admin/getAllNotice/{currPage}/{pageNum}")
    @TokenValid
    public BaseResponse getNoticeList(@PathVariable Integer pageNum, @PathVariable Integer currPage) {

        Page<NoticeEntity> page = new Page<>(currPage, pageNum);
        Page<NoticeEntity> entities = noticeService.page(page);
        List<NoticeEntity> records = entities.getRecords();

        if (CollectionUtil.isNotEmpty(records)) {
            BaseResponse success = new BaseResponse(SystemStatusEnum.SUCCESS);
            success.setData(entities);
            success.setTotal(page.getTotal());
            return success;
        } else {
            return new BaseResponse(SystemStatusEnum.SUCCESS.getCode(), "获取数据为空！");
        }
    }

    /**
     * 我的通知分页获取数据与数量
     *
     * @return
     */
    @ApiOperation(value = "我的通知分页获取数据与数量", notes = "我的通知分页获取数据与数量")
    @GetMapping("students/getNotice/{uId}/{currPage}/{pageNum}")
    @TokenValid
    public BaseResponse getNoticeList(@PathVariable Integer uId, @PathVariable Integer pageNum, @PathVariable Integer currPage) {

        UserEntity userEntity = userService.getById(uId);
        if (userEntity == null) {
            return new BaseResponse(SystemStatusEnum.FAIL.getCode(), "用户不存在！");
        }
        String classes = userEntity.getClasses();
        if (StringUtils.isBlank(classes)) {
            return new BaseResponse(SystemStatusEnum.SUCCESS.getCode(), "未找到班级！");
        }
        Page<NoticeEntity> page = new Page<>(currPage, pageNum);
        Page<NoticeEntity> entities = noticeService.page(page, Wrappers.lambdaQuery(new NoticeEntity())
                .like(NoticeEntity::getClasses, classes).orderByDesc(NoticeEntity::getNId));
        List<NoticeEntity> records = entities.getRecords();

        if (CollectionUtil.isNotEmpty(records)) {
            BaseResponse success = new BaseResponse(SystemStatusEnum.SUCCESS);
            success.setData(entities);
            success.setTotal(page.getTotal());
            return success;
        } else {
            return new BaseResponse(SystemStatusEnum.SUCCESS.getCode(), "获取数据为空！");
        }
    }

    /**
     * 当前公告查看详情
     *
     * @return
     */
    @ApiOperation(value = "当前公告查看详情", notes = "当前公告查看详情")
    @GetMapping("admin/NoticeDetails/{nId}")
    @TokenValid
    public Map<Object, Object> getNoticeList(@PathVariable Integer nId) {

        LOGGER.info("查看当前公告详情接口,参数：{}", nId);
        LambdaQueryWrapper<ReadEntity> wrapper = Wrappers.lambdaQuery(new ReadEntity()).eq(ReadEntity::getNId, nId);
        //1. 获取当前公告已读人的人数
        int count = readService.count(wrapper);
        //2. 获取当前公告已读的人的id数组,再通过id去查询用户数据
        List<ReadEntity> readEntities = readService.list(wrapper.select(ReadEntity::getUId));
        List<Integer> userIdList = readEntities.stream().map(ReadEntity::getUId).collect(Collectors.toList());
        List<UserEntity> userEntities = new ArrayList<>();
        if (!CollectionUtil.isEmpty(userIdList)) {
            userEntities = userService.listByIds(userIdList);
        }
        //3. 获取当前通知的详情信息
        NoticeEntity noticeEntity = noticeService.getById(nId);
        String[] split = noticeEntity.getClasses().split(",");
        List<String> classes = Arrays.asList(split);
        //4. 获取当前公告通知的总人数
        int totalUser = userService.count(Wrappers.lambdaQuery(new UserEntity()).in(UserEntity::getClasses, classes));
        //5. 获取已读人的阅读时间与uid
        wrapper.clear();
        List<ReadEntity> readEntities1 = readService.list(wrapper.eq(ReadEntity::getNId, nId));
        HashMap<Object, Object> map = new HashMap<>();
        map.put("data", noticeEntity);
        map.put("tatol", totalUser);
        map.put("readNum", count);
        ArrayList<GetNoticeVO> getNoticeVOS = new ArrayList<>();
        for (UserEntity userEntity : userEntities) {
            GetNoticeVO getNoticeVO = new GetNoticeVO();
            BeanUtil.copyProperties(userEntity, getNoticeVO);
            for (ReadEntity readEntity : readEntities1) {
                if (readEntity.getUId().compareTo(getNoticeVO.getId()) == 0) {
                    getNoticeVO.setReadtime(readEntity.getReadtime());
                }
            }
            getNoticeVOS.add(getNoticeVO);
        }
        map.put("users", getNoticeVOS);
        map.put("code", 0);
        map.put("message", "成功");
        return map;
    }

}
